package com.oracle.lingshangejia.activity.special;

import android.app.DatePickerDialog;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.CheckBox;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.widget.RadioButton;
import android.widget.Spinner;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.oracle.lingshangejia.Constant;
import com.oracle.lingshangejia.R;
import com.oracle.lingshangejia.adapter.special.ET12ArchivesExtendableListAdapter;
import com.oracle.lingshangejia.bean.DataBean;
import com.oracle.lingshangejia.bean.ParentsBean;
import com.oracle.lingshangejia.bean.User;
import com.oracle.lingshangejia.dialog.LoadingViewDialog;
import com.oracle.lingshangejia.model.OkgoNetwork;
import com.oracle.lingshangejia.utils.MyLogger;
import com.oracle.lingshangejia.utils.MyToast;
import com.oracle.lingshangejia.utils.ObserverOnNext;
import com.oracle.lingshangejia.utils.RxUtils;

import org.json.JSONObject;

import java.util.Arrays;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;

//儿童12
public class ErTong12ArchivesActivity extends AppCompatActivity {
    private ExpandableListView expandableListView;
    private ET12ArchivesExtendableListAdapter archivesExtendableListAdapter;


    private static int[] childItems = {R.layout.et12_twelvechilds_item_0, R.layout.et12_twelvechilds_item_1, R.layout.et12_twelvechilds_item_2, R.layout.et12_twelvechilds_item_3};
    // 用于存放折叠的视图
    private View[] viewss  = new View[childItems.length];

    private Spinner ageSpinner;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.et12_add_archives_activity);
        initBasic();
        ageSpinner = findViewById(R.id.archives_ageOfTheMoon_12);


        expandableListView = findViewById(R.id.expend_list);
        expandableListView.setGroupIndicator(null);
        String[] archivesStr = getResources().getStringArray(R.array.et_12_archives);
        archivesExtendableListAdapter = new ET12ArchivesExtendableListAdapter(archivesStr);
        for(int i = 0; i < viewss.length; i++) {
            viewss[i] = LayoutInflater.from(expandableListView.getContext()).inflate(childItems[i], expandableListView, false);
        }
        archivesExtendableListAdapter.setConvertViews(viewss);
        expandableListView.setAdapter(archivesExtendableListAdapter);
        // 添加末尾提交按钮
        View foot = LayoutInflater.from(this).inflate(R.layout.archives_foot_submit, null);
        expandableListView.addFooterView(foot);

        expandableListView.setOnGroupExpandListener(new ExpandableListView.OnGroupExpandListener() {
            @Override
            public void onGroupExpand(int groupPosition) {
                // 页面没加载时不折叠
                if(viewss == null)
                    return;
                int count = expandableListView.getExpandableListAdapter().getGroupCount();
                for (int i = 0; i < count; i++) {
                    if (i != groupPosition) {
                        expandableListView.collapseGroup(i);
                    }
                }

            }
        });

        ageSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                //取得被选中的列表项的文字
                String age = parent.getItemAtPosition(position).toString();
                for(View v:viewss) {
                    System.out.println("视图：" + v);
                }
                TableRow bregma = viewss[2].findViewById(R.id.bregma);
                TableRow hearing = viewss[2].findViewById(R.id.hearing);
                TableRow Gait = viewss[2].findViewById(R.id.Gait);
                TableLayout Suspicious = viewss[2].findViewById(R.id.twelveChilds_Suspicious);
                TableRow HemoglobinValue = viewss[2].findViewById(R.id.HemoglobinValue);

                TableRow TakeVitaminD = viewss[3].findViewById(R.id.TakeVitaminD);
                TableRow Developmental1 = viewss[3].findViewById(R.id.Developmental1);
                TableRow Developmental2 = viewss[3].findViewById(R.id.Developmental2);
                TableRow Developmental3 = viewss[3].findViewById(R.id.Developmental3);
                TableRow Developmental4 = viewss[3].findViewById(R.id.Developmental4);
                TableLayout guide1 = viewss[3].findViewById(R.id.twelveChilds_guide1);
                TableLayout guide2 = viewss[3].findViewById(R.id.twelveChilds_guide2);

                if("1 12月龄".equals(age)) {
                    bregma.setVisibility(View.VISIBLE);
                    hearing.setVisibility(View.VISIBLE);
                    Suspicious.setVisibility(View.VISIBLE);
                    TakeVitaminD.setVisibility(View.VISIBLE);
                    Developmental1.setVisibility(View.VISIBLE);
                    guide1.setVisibility(View.VISIBLE);

                    Gait.setVisibility(View.GONE);
                    HemoglobinValue.setVisibility(View.GONE);
                    Developmental2.setVisibility(View.GONE);
                    Developmental3.setVisibility(View.GONE);
                    Developmental4.setVisibility(View.GONE);
                    guide2.setVisibility(View.GONE);
                }
                if("2 18月龄".equals(age)) {
                    bregma.setVisibility(View.VISIBLE);
                    Gait.setVisibility(View.VISIBLE);
                    Suspicious.setVisibility(View.VISIBLE);
                    HemoglobinValue.setVisibility(View.VISIBLE);
                    TakeVitaminD.setVisibility(View.VISIBLE);
                    Developmental2.setVisibility(View.VISIBLE);
                    guide1.setVisibility(View.VISIBLE);



                    Developmental1.setVisibility(View.GONE);
                    Developmental3.setVisibility(View.GONE);
                    Developmental4.setVisibility(View.GONE);
                    guide2.setVisibility(View.GONE);
                    hearing.setVisibility(View.GONE);
                }
                if("3 24月龄".equals(age)) {
                    bregma.setVisibility(View.VISIBLE);
                    hearing.setVisibility(View.VISIBLE);
                    Gait.setVisibility(View.VISIBLE);
                    Suspicious.setVisibility(View.VISIBLE);
                    TakeVitaminD.setVisibility(View.VISIBLE);
                    Developmental3.setVisibility(View.VISIBLE);
                    guide2.setVisibility(View.VISIBLE);


                    HemoglobinValue.setVisibility(View.GONE);
                    Developmental2.setVisibility(View.GONE);
                    Developmental1.setVisibility(View.GONE);
                    Developmental4.setVisibility(View.GONE);
                    guide1.setVisibility(View.GONE);
                }
                if("4 30月龄".equals(age)) {
                    bregma.setVisibility(View.VISIBLE);
                    HemoglobinValue.setVisibility(View.VISIBLE);
                    Developmental4.setVisibility(View.VISIBLE);
                    guide2.setVisibility(View.VISIBLE);


                    hearing.setVisibility(View.GONE);
                    Gait.setVisibility(View.GONE);
                    Suspicious.setVisibility(View.GONE);
                    TakeVitaminD.setVisibility(View.GONE);
                    Developmental2.setVisibility(View.GONE);
                    Developmental3.setVisibility(View.GONE);
                    Developmental1.setVisibility(View.GONE);
                    guide1.setVisibility(View.GONE);
                }
                // 获取数据后只留第一个展开，其余关闭
                int count = expandableListView.getExpandableListAdapter().getGroupCount();
                for (int i = 0; i < count; i++) {
                    if(i == 0) {
                        expandableListView.expandGroup(i);
                    } else {
                        expandableListView.collapseGroup(i);
                    }
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        // 页面加载完展开所有数据，用于获取视图数据
        int count = expandableListView.getExpandableListAdapter().getGroupCount();
        for (int i = 0; i < count; i++) {
            expandableListView.expandGroup(i);
        }

        expandableListView.setOnGroupCollapseListener(new ExpandableListView.OnGroupCollapseListener() {
            @Override
            public void onGroupCollapse(int groupPosition) {
                View[] views = ((ET12ArchivesExtendableListAdapter) expandableListView.getExpandableListAdapter()).getConvertViews();
                View view = views[groupPosition];
                if (view == null) {
                    return;
                }
                Map<String, String> values = null;
                switch (groupPosition) {
                    case 0:
                        values = getBasicInfoValues();
                        break;
                    case 1:
                        values = getPhysicalConditionValues(view);
                        break;
                    case 2:
                        values = getPhysicalExaminationValues(view);
                        break;
                    case 3:
                        values = getGrowthSituationValues(view);
                        break;
                }


            }
        });

        expandableListView.expandGroup(0);

    }


    /**
     * 检查用户名、身份证号和本人联系电话是否正确填写
     *
     * @return 数据不正确返回true，正确返回false
     */
    private boolean checkBasicInfoIsError() {
        Map<String, String> basicInforValues = getBasicInfoValues();
        String xm = (String) basicInforValues.get("xm");
        // 姓名非空验证
        if (xm == null || xm.length() == 0) {
            Toast.makeText(getApplicationContext(), "姓名必须填写", Toast.LENGTH_SHORT).show();
            return true;
        }

        return false;
    }




    /**
     * 第一页 获取基本信息数据
     */
    private Map<String, String> getBasicInfoValues() {
        View[] views = ((ET12ArchivesExtendableListAdapter) expandableListView.getExpandableListAdapter()).getConvertViews();
        View view = views[0];
        Map<String, String> params = new HashMap<>();
        //姓名
        String Name = "";
        // 居民id
        String residentID = "";
        // 父亲姓名
        String fatherName = "";
        // 母亲姓名
        String motherName = "";
        // 父亲职业
        String fatherOccupation = "";
        // 母亲职业
        String motherOccupation = "";
        // 父亲电话
        String fatherTel = "";
        // 母亲电话
        String motherTel = "";
        // 父亲出生日期
        String fatherBirth = "";
        // 母亲出生日期
        String motherBirth = "";
        // 医生id
        String doctorID = "";
        //月龄
        String age="";



      //  Name = ((EditText) view.findViewById(R.id.twelveChilds_name)).getText().toString().trim();
      //  residentID = ((EditText) view.findViewById(R.id.twelveChilds_residentID)).getText().toString().trim();
        fatherName = ((EditText) view.findViewById(R.id.twelveChilds_fatherName)).getText().toString().trim();
        motherName = ((EditText) view.findViewById(R.id.twelveChilds_motherName)).getText().toString().trim();
        fatherOccupation = ((EditText) view.findViewById(R.id.twelveChilds_fatherJob)).getText().toString().trim();
        motherOccupation = ((EditText) view.findViewById(R.id.twelveChilds_motherJob)).getText().toString().trim();
        fatherTel = ((EditText) view.findViewById(R.id.twelveChilds_fatherTel)).getText().toString().trim();
        motherTel = ((EditText) view.findViewById(R.id.twelveChilds_motherTel)).getText().toString().trim();
        fatherBirth = ((TextView) view.findViewById(R.id.twelveChilds_fatherBirth)).getText().toString().trim();
        motherBirth = ((TextView) view.findViewById(R.id.twelveChilds_motherBirth)).getText().toString().trim();
      //  doctorID = ((EditText) view.findViewById(R.id.twelveChilds_doctorID)).getText().toString().trim();
        age = ((Spinner) findViewById(R.id.archives_ageOfTheMoon_12)).getSelectedItem().toString().trim();
        age = age.substring(0, age.indexOf(" "));

      //  params.put("xm", Name);
       // params.put("grjbxx_id", residentID);
        params.put("fxm", fatherName);
        params.put("mxm", motherName);
        params.put("fzy", fatherOccupation);
        params.put("mzy", motherOccupation);
        params.put("fdh", fatherTel);
        params.put("mdh", motherTel);
        params.put("fcsrq", fatherBirth);
        params.put("mcsrq", motherBirth);
       // params.put("create_by", doctorID);
        params.put("yl", age);
        mValues.putAll(params);
        MyLogger.i((new JSONObject(params).toString()));
        return params;
    }

    /**
     * 第二页 获取身体状况数据
     */
    private Map<String, String> getPhysicalConditionValues(View view) {
        Map<String, String> params = new HashMap<>();
        //随访日期
        String FollowUpDate = "";
        //体重
        String Weight = "";
        //身长
        String Length = "";
       // FollowUpDate = ((TextView) view.findViewById(R.id.twelveChilds_FollowUpDate)).getText().toString().trim();
        Weight = ((Spinner) view.findViewById(R.id.twelveChilds_weight)).getSelectedItem().toString().trim();
        Weight = Weight.substring(0, Weight.indexOf(" "));
        Length = ((Spinner) view.findViewById(R.id.twelveChilds_Length)).getSelectedItem().toString().trim();
        Length = Length.substring(0, Length.indexOf(" "));

        //params.put("sfrq", FollowUpDate);
        params.put("xseTz", Weight);//体重
        params.put("xseSz", Length);//身高
        mValues.putAll(params);
        return params;
    }

    /**
     * 第三页 获取体格检测数据
     */
    private Map<String, String> getPhysicalExaminationValues(View view) {
        Map<String, String> params = new HashMap<>();
        //面色
        String Complexion = "";
        //皮肤
        String  Skin= "";
        //前囟
        String AnteriorFontanelle = "";
//        String AnteriorFontanelle1 = "";
//        String AnteriorFontanelle2 = "";
        //眼睛
        String Eyes = "";
        //耳外观
        String Ear = "";
        //听力
        String Hearing = "";
        //胸部
        String Chest = "";
        //腹部
        String Abdomen = "";
        //四肢
        String Limb = "";
        //步态
        String Gait = "";
        //可疑佝偻病体征
        String SuspiciousSignsOfRickets = "";
        //血红蛋白值
        String HemoglobinValue = "";
        Complexion = ((Spinner) view.findViewById(R.id.twelveChilds_Complexion)).getSelectedItem().toString().trim();
        Complexion = Complexion.substring(0, Complexion.indexOf(" "));
        Skin = ((Spinner) view.findViewById(R.id.twelveChilds_skin)).getSelectedItem().toString().trim();
        Skin = Skin.substring(0, Skin.indexOf(" "));
//        if (((RadioButton) view.findViewById(R.id.twelveChilds_close)).isChecked()) {
//            AnteriorFontanelle = "闭合";
//            AnteriorFontanelle1 = null;
//            AnteriorFontanelle2 = null;
//        } else {
//            AnteriorFontanelle = "未闭";
//            AnteriorFontanelle1= ((EditText) view.findViewById(R.id.twelveChilds_bregma1)).getText().toString().trim();
//            AnteriorFontanelle2= ((EditText) view.findViewById(R.id.twelveChilds_bregma2)).getText().toString().trim();
//        }
        AnteriorFontanelle = ((Spinner) view.findViewById(R.id.onenewborn_bregma)).getSelectedItem().toString().trim();
        AnteriorFontanelle = AnteriorFontanelle.substring(0, AnteriorFontanelle.indexOf(" "));
        Eyes = ((Spinner) view.findViewById(R.id.twelveChilds_eye)).getSelectedItem().toString().trim();
        Eyes = Eyes.substring(0, Eyes.indexOf(" "));
        Ear = ((Spinner) view.findViewById(R.id.twelveChilds_ear)).getSelectedItem().toString().trim();
        Ear = Ear.substring(0, Ear.indexOf(" "));
        Hearing = ((Spinner) view.findViewById(R.id.twelveChilds_hearing)).getSelectedItem().toString().trim();
        Hearing = Hearing.substring(0, Hearing.indexOf(" "));
        Chest = ((Spinner) view.findViewById(R.id.twelveChilds_chest)).getSelectedItem().toString().trim();
        Chest = Chest.substring(0, Chest.indexOf(" "));
        Abdomen = ((Spinner) view.findViewById(R.id.twelveChilds_Abdomen)).getSelectedItem().toString().trim();
        Abdomen = Abdomen.substring(0, Abdomen.indexOf(" "));
        Limb = ((Spinner) view.findViewById(R.id.twelveChilds_limb)).getSelectedItem().toString().trim();
        Limb = Limb.substring(0, Limb.indexOf(" "));
        Gait = ((Spinner) view.findViewById(R.id.twelveChilds_Gait)).getSelectedItem().toString().trim();
        Gait = Gait.substring(0, Gait.indexOf(" "));
        View[] Suspicious = getViews(view.findViewById(R.id.twelveChilds_Suspicious));
        for (int i = 0; i < Suspicious.length; i++) {
            if (Suspicious[i] instanceof CheckBox) {
                CheckBox cb = (CheckBox) Suspicious[i];
                if (cb.isChecked()) {
                    String s = cb.getText().toString().trim();
                    s = s.substring(0, s.indexOf(" "));
                    SuspiciousSignsOfRickets += s;
                    SuspiciousSignsOfRickets += ",";
                }
            }
        }
        if (SuspiciousSignsOfRickets.length() != 0) {
            SuspiciousSignsOfRickets = SuspiciousSignsOfRickets.substring(0, SuspiciousSignsOfRickets.length() - 1);
        }
        HemoglobinValue = ((EditText) view.findViewById(R.id.twelveChilds_HemoglobinValue)).getText().toString().trim();
        MyLogger.i(SuspiciousSignsOfRickets+"佝偻病");
        params.put("xseMs", Complexion);//面色
        params.put("xsePf", Skin);//皮肤
        params.put("xseQl", AnteriorFontanelle);//前囟
      // params.put("xse_ql1", AnteriorFontanelle);//
//        params.put("xse_ql2", AnteriorFontanelle2);//
        params.put("xseYj", Eyes);//眼睛
        params.put("xseEd", Ear);//耳朵
        params.put("xseTl", Hearing);//听力
        params.put("xseXb", Chest);//胸部
        params.put("xseFb", Abdomen);///腹部
        params.put("xseSzhd", Limb);//四肢
        params.put("xseBt", Gait);//步态
        params.put("xseKyglbtz", SuspiciousSignsOfRickets);///可疑佝偻病体征
        params.put("xseXhdbz", HemoglobinValue);//红蛋白
        mValues.putAll(params);
        return params;
    }

    /**
     * 第四页 获取成长状况数据
     */
    private Map<String, String> getGrowthSituationValues(View view) {
        Map<String, String> params = new HashMap<>();
        //户外活动
        String OutdoorActivities="";
        //服用维生素D
        String TakeVitaminD="";
        //发育评估
        String DevelopmentalAssessment1="";
        String DevelopmentalAssessment2="";
        String DevelopmentalAssessment3="";
        String DevelopmentalAssessment4="";
        //两次随访间患病情况
        String Disease = "";
        String DiseaseTime="";
        String otherDisease="";
        String DiseasepneumoniaTime="";
        String DiseasediarrheaTime="";
        String DiseasetraumaTime="";
        //转诊建议
        String ReferralSuggestion="";
        String ReferralSuggestionReason="";
        //机构及科室
        String InstitutionsAndDepartments="";
        //指导
        String Guidance="";
        String otherGuidance1="";
        String otherGuidance2="";
        //下次随访日期
        String NextFollowUpDate="";
        //随访医生签名
        String DoctorSignature="";
        OutdoorActivities = ((EditText) view.findViewById(R.id.twelveChilds_outdoorActivities)).getText().toString().trim();
        TakeVitaminD = ((EditText) view.findViewById(R.id.twelveChilds_TakeVitaminD)).getText().toString().trim();
        //12月
        View[] AssessmentViews1 = getViews(view.findViewById(R.id.twelveChilds_Developmental1));
        for (int i = 0; i < AssessmentViews1.length; i++) {
            if (AssessmentViews1[i] instanceof CheckBox) {
                CheckBox cb = (CheckBox) AssessmentViews1[i];
                if (cb.isChecked()) {
                    String s = cb.getText().toString().trim();
                    s = s.substring(0, s.indexOf(" "));
                    DevelopmentalAssessment1 += s;
                    DevelopmentalAssessment1 += ",";
                }
            }
        }
        if (DevelopmentalAssessment1.length() != 0) {
            DevelopmentalAssessment1 = DevelopmentalAssessment1.substring(0, DevelopmentalAssessment1.length() - 1);
        }
        //18月
        View[] AssessmentViews2 = getViews(view.findViewById(R.id.twelveChilds_Developmental2));
        for (int i = 0; i < AssessmentViews2.length; i++) {
            if (AssessmentViews2[i] instanceof CheckBox) {
                CheckBox cb = (CheckBox) AssessmentViews2[i];
                if (cb.isChecked()) {
                    String s = cb.getText().toString().trim();
                    s = s.substring(0, s.indexOf(" "));
                    DevelopmentalAssessment2 += s;
                    DevelopmentalAssessment2 += ",";
                }
            }
        }
        if (DevelopmentalAssessment2.length() != 0) {
            DevelopmentalAssessment2 = DevelopmentalAssessment2.substring(0, DevelopmentalAssessment2.length() - 1);
        }
        //24月
        View[] AssessmentViews3 = getViews(view.findViewById(R.id.twelveChilds_Developmental3));
        for (int i = 0; i < AssessmentViews3.length; i++) {
            if (AssessmentViews3[i] instanceof CheckBox) {
                CheckBox cb = (CheckBox) AssessmentViews3[i];
                if (cb.isChecked()) {
                    String s = cb.getText().toString().trim();
                    s = s.substring(0, s.indexOf(" "));
                    DevelopmentalAssessment3 += s;
                    DevelopmentalAssessment3 += ",";
                }
            }
        }
        if (DevelopmentalAssessment3.length() != 0) {
            DevelopmentalAssessment3 = DevelopmentalAssessment3.substring(0, DevelopmentalAssessment3.length() - 1);
        }
        //30月
        View[] AssessmentViews4 = getViews(view.findViewById(R.id.twelveChilds_Developmental4));
        for (int i = 0; i < AssessmentViews4.length; i++) {
            if (AssessmentViews4[i] instanceof CheckBox) {
                CheckBox cb = (CheckBox) AssessmentViews4[i];
                if (cb.isChecked()) {
                    String s = cb.getText().toString().trim();
                    s = s.substring(0, s.indexOf(" "));
                    DevelopmentalAssessment4 += s;
                    DevelopmentalAssessment4 += ",";
                }
            }
        }
        if (DevelopmentalAssessment4.length() != 0) {
            DevelopmentalAssessment4 = DevelopmentalAssessment4.substring(0, DevelopmentalAssessment4.length() - 1);
        }

        DiseasepneumoniaTime=((EditText) view.findViewById(R.id.twelveChilds_DiseaseTwo_pneumonia_time)).getText().toString().trim();
        DiseasediarrheaTime=((EditText) view.findViewById(R.id.twelveChilds_DiseaseTwo_diarrhea_time)).getText().toString().trim();
        DiseasetraumaTime=((EditText) view.findViewById(R.id.twelveChilds_DiseaseTwo_trauma_time)).getText().toString().trim();
        if (((RadioButton) view.findViewById(R.id.twelveChilds_DiseaseTwo_none)).isChecked()) {
            Disease = "1";
        } else if(((RadioButton) view.findViewById(R.id.twelveChilds_DiseaseTwo_pneumonia)).isChecked()){
            Disease = "2";
            DiseaseTime = DiseasepneumoniaTime;
        }else if(((RadioButton) view.findViewById(R.id.twelveChilds_DiseaseTwo_diarrhea)).isChecked()){
            Disease = "3";
            DiseaseTime = DiseasediarrheaTime;
        }else if(((RadioButton) view.findViewById(R.id.twelveChilds_DiseaseTwo_trauma)).isChecked()){
            Disease = "4";
            DiseaseTime = DiseasetraumaTime;
        }else{
            Disease = "5";
        }
        otherDisease = ((TextView) view.findViewById(R.id.twelveChilds_DiseaseTwo_otherIll)).getText().toString().trim();

        if (view != null) {
            RadioButton none = view.findViewById(R.id.twelveChilds_none);
            RadioButton all = view.findViewById(R.id.twelveChilds_genetic_disease_all);
            if (none.isChecked()) {
                String s = none.getText().toString().trim();
                s = s.substring(0, s.indexOf(" "));
                ReferralSuggestion = s;
            } else {
                String s = all.getText().toString().trim();
                if(s.length() > 0)
                    s = s.substring(0, s.indexOf(" "));
                ReferralSuggestion = s;
            }
            ReferralSuggestionReason = ((EditText) view.findViewById(R.id.twelveChilds_Reason)).getText().toString().trim();
            InstitutionsAndDepartments = ((EditText) view.findViewById(R.id.twelveChilds_mechanism)).getText().toString().trim();
        }

        TableLayout table = ((TableLayout) view.findViewById(R.id.twelveChilds_guide1));
        View[] cbs = getViews(table);
        for (int i = 0; i < cbs.length; i++) {
            if (cbs[i] instanceof CheckBox) {
                CheckBox cb = (CheckBox) cbs[i];
                if (cb.isChecked()) {
                    String s = cb.getText().toString().trim();
                    s = s.substring(0, s.indexOf(" "));
                    Guidance += s;
                    Guidance += ",";
                }
            }
        }
        if (Guidance.length() != 0) {
            Guidance = Guidance.substring(0, Guidance.length() - 1);
        }
        otherGuidance1 = ((EditText) view.findViewById(R.id.twelveChilds_guidance_other_text1)).getText().toString().trim();
        otherGuidance2 = ((EditText) view.findViewById(R.id.twelveChilds_guidance_other_text2)).getText().toString().trim();
        NextFollowUpDate = ((TextView) view.findViewById(R.id.twelveChilds_NextDate)).getText().toString().trim();
        DoctorSignature = ((EditText) view.findViewById(R.id.twelveChilds_signature)).getText().toString().trim();

        params.put("hwhd", OutdoorActivities);	//户外活动(小时/日）
        params.put("fywssd", TakeVitaminD);//服用维生素D（IU/日)

        //发育评估（
        if (!TextUtils.isEmpty(DevelopmentalAssessment1)) {
            params.put("fypg", DevelopmentalAssessment1); //发育评估
        }
        if (!TextUtils.isEmpty(DevelopmentalAssessment2)) {
            params.put("fypg", DevelopmentalAssessment2); //发育评估
        }
        if (!TextUtils.isEmpty(DevelopmentalAssessment3)) {
            params.put("fypg", DevelopmentalAssessment3); //发育评估
        }
        if (!TextUtils.isEmpty(DevelopmentalAssessment4)) {
            params.put("fypg", DevelopmentalAssessment4); //发育评估
        }


        params.put("lcsfjhbqk", Disease);//两次随访间患者患病情况（1
        params.put("lcsfjhzqkQt", otherDisease);//两次随访间患者患病情况_其他
        params.put("lcsfjhzqkCs2",DiseasepneumoniaTime);//肺炎次数
        params.put("lcsfjhzqkCs3",DiseasediarrheaTime);//腹泻次数
        params.put("lcsfjhzqkCs4",DiseasetraumaTime);//外伤次数
        params.put("zzjy",ReferralSuggestion);////转诊建议
        params.put("zzjyYy",ReferralSuggestionReason);//原因
        params.put("zzjyJgjks",InstitutionsAndDepartments);//科室
        params.put("zd",Guidance);//指导
        if (!TextUtils.isEmpty(otherGuidance1)) {
            params.put("zdQt", otherGuidance1);//其他 指导
        }
        if (!TextUtils.isEmpty(otherGuidance2)) {
            params.put("zdQt", otherGuidance2);//其他 指导
        }

        params.put("scsfsj",NextFollowUpDate);//下次随访
        params.put("sfysqm",DoctorSignature);//签名
        mValues.putAll(params);
        return params;
    }


    /**
     * Toolbar的事件---返回
     */
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
        }
        return super.onOptionsItemSelected(item);
    }

    /**
     * 点击日期选择框弹出DatePickerDialog
     */
    private Calendar calendar;
    private DatePickerDialog dialog;

    public void onTimeViewClick(final View v) {
        calendar = Calendar.getInstance();
        dialog = new DatePickerDialog(ErTong12ArchivesActivity.this,
                new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker view, int year,
                                          int monthOfYear, int dayOfMonth) {
                        TextView tv = (TextView) v;
                        String month;
                        String day;
                        if (monthOfYear <9){
                            month = "0"+(monthOfYear+1);
                        }else {
                            month = ""+(monthOfYear+1);
                        }
                        if (dayOfMonth <10){
                            day = "0"+dayOfMonth;
                        }else {
                            day = dayOfMonth + "";
                        }
                        tv.setText(year + "-" + month  + "-" + day);
                    }
                }, calendar.get(Calendar.YEAR), calendar
                .get(Calendar.MONTH), calendar
                .get(Calendar.DAY_OF_MONTH));
        dialog.show();
    }

//    /**
//     * 前囟点击事件
//     */
//    public void onAnteriorFontanelleEdit(View view) {
//        EditText ed1 = findViewById(R.id.twelveChilds_bregma1);
//        EditText ed2 = findViewById(R.id.twelveChilds_bregma2);
//        RadioButton rb = (RadioButton) view;
//        if (view.getId() == R.id.twelveChilds_close) {
//            ed1.setText("");
//            ed1.setEnabled(false);
//            ed2.setText("");
//            ed2.setEnabled(false);
//        } else if (rb.isChecked()) {
//            ed1.setEnabled(true);
//            ed1.setFocusable(true);
//            ed1.setFocusableInTouchMode(true);
//            ed1.requestFocus();
//            ed2.setEnabled(true);
//            ed2.setFocusable(true);
//            ed2.setFocusableInTouchMode(true);
//            ed2.requestFocus();
//        }
//    }

    /**
     * "可疑佝偻病体征"按钮点击事件处理
     */
    public void onSuspiciousClick(View view) {
        View[] views = getViews(findViewById(R.id.twelveChilds_Suspicious));
        CheckBox none = findViewById(R.id.twelveChilds_Suspicious_none);
        boolean flag = false;
        for (int i = 0; i < views.length; i++) {
            if (views[i] instanceof CheckBox) {
                CheckBox cb = (CheckBox) views[i];
                if (cb.isChecked()) {
                    flag = true;
                }
                if (view == none) {
                    if (none.isChecked() && cb != none) {
                        cb.setChecked(false);
                    }
                } else {
                    CheckBox v = (CheckBox) view;
                    if (v.isChecked()) {
                        none.setChecked(false);
                    }
                }
            }
        }
        if (flag != true) {
            none.setChecked(true);
        }
    }

    /**
     * "转诊建议"按钮点击事件处理
     */
    public void onEdit(View view) {
        EditText ed1 = findViewById(R.id.twelveChilds_Reason);
        EditText ed2 = findViewById(R.id.twelveChilds_mechanism);
        RadioButton rb = (RadioButton) view;
        if (view.getId() == R.id.twelveChilds_none) {
            ed1.setText("");
            ed1.setEnabled(false);
            ed2.setText("");
            ed2.setEnabled(false);
        } else if (rb.isChecked()) {
            ed1.setEnabled(true);
            ed2.setEnabled(true);
        }
    }

    /**
     * "指导"按钮点击事件处理
     */
    public void onGuideClick(View view) {
        View[] views = getViews(findViewById(R.id.twelveChilds_guide1));
        CheckBox other = findViewById(R.id.twelveChilds_guidance_other1);
        EditText otherText = findViewById(R.id.twelveChilds_guidance_other_text1);
        boolean flag = false;
        for (int i = 0; i < views.length; i++) {
            if (views[i] instanceof CheckBox) {
                CheckBox cb = (CheckBox) views[i];
                if (cb.isChecked()) {
                    flag = true;
                }
            }
        }
        if (other.isChecked()) {
            otherText.setEnabled(true);
            otherText.setFocusable(true);
            otherText.setFocusableInTouchMode(true);
            otherText.requestFocus();
        } else {
            otherText.setEnabled(false);
            otherText.setText("");
        }
    }


    /**
     * 两次随访间患病情况按钮点击事件
     */
    public void onDiseaseTwoClick(View view) {
        EditText ed1 = findViewById(R.id.twelveChilds_DiseaseTwo_pneumonia_time);
        EditText ed2 = findViewById(R.id.twelveChilds_DiseaseTwo_diarrhea_time);
        EditText ed3 = findViewById(R.id.twelveChilds_DiseaseTwo_trauma_time);
        EditText ed4 = findViewById(R.id.twelveChilds_DiseaseTwo_otherIll);
        if (view.getId() == R.id.twelveChilds_DiseaseTwo_none) {
            ed1.setText("");
            ed1.setEnabled(false);
            ed2.setText("");
            ed2.setEnabled(false);
            ed3.setText("");
            ed3.setEnabled(false);
            ed4.setText("");
            ed4.setEnabled(false);
        } else if (view.getId() == R.id.twelveChilds_DiseaseTwo_pneumonia) {
            ed1.setEnabled(true);
            ed1.setFocusable(true);
            ed1.setFocusableInTouchMode(true);
            ed1.requestFocus();
        }else if (view.getId() == R.id.twelveChilds_DiseaseTwo_diarrhea) {
            ed2.setEnabled(true);
            ed2.setFocusable(true);
            ed2.setFocusableInTouchMode(true);
            ed2.requestFocus();
        }else if (view.getId() == R.id.twelveChilds_DiseaseTwo_trauma) {
            ed3.setEnabled(true);
            ed3.setFocusable(true);
            ed3.setFocusableInTouchMode(true);
            ed3.requestFocus();
        }else if (view.getId() == R.id.twelveChilds_DiseaseTwo_other) {
            ed4.setEnabled(true);
            ed4.setFocusable(true);
            ed4.setFocusableInTouchMode(true);
            ed4.requestFocus();
        }
    }

    /**
     * 获取子视图
     */
    private View[] views;

    private View[] getViews(View view) {
        views = new View[0];
        parseView(view);
        return views;
    }

    private void parseView(View view) {
        if (view instanceof ViewGroup) {
            ViewGroup vg = (ViewGroup) view;
            for (int i = 0; i < vg.getChildCount(); i++) {
                View v = vg.getChildAt(i);
                parseView(v);
            }
        } else {
            views = Arrays.copyOf(views, views.length + 1);
            views[views.length - 1] = view;
        }
    }

    /**
     * 提交数据
     */
    public void onClickSubmit(View view) {
        showLoading();
        int count = expandableListView.getExpandableListAdapter().getGroupCount();
        for (int i = 0; i < count; i++) {
            expandableListView.collapseGroup(i);
        }
        Observable.create(new ObservableOnSubscribe<DataBean>() {
            @Override
            public void subscribe(ObservableEmitter<DataBean> emitter) throws Exception {
                JSONObject jsonObject = new JSONObject(mValues);
                MyLogger.i(jsonObject.toString());
                String json = OkgoNetwork.post(url,jsonObject.toString());
                MyLogger.i(json);
                Gson gson = new Gson();
                emitter.onNext(gson.fromJson(json, DataBean.class));

            }
        }).compose(RxUtils.io_main()).subscribe(new ObserverOnNext<DataBean>() {
            @Override
            public void onNext(DataBean dataBean) {
                if (dataBean.getCode()==0){
                    MyToast.show("提交成功");
                    finish();
                }else {
                    MyToast.show(dataBean.getMsg());
                }
                dismissLoading();

            }
        });

    }

    private ParentsBean mParentsBean;
    //新
    private Map<Object,Object> mValues = new HashMap<>();
    private  String url = Constant.baseurl+"online/xseSrdss/save";
    private LoadingViewDialog mLoadingView;
    //整合专项  基础 修改
    private void initBasic(){
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        Toolbar toolbar = (Toolbar)findViewById(com.oracle.children.R.id.toolbar);
        toolbar.setTitle("");
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        mValues.put("token", User.getToken());
        mValues.put("jmId",getIntent().getIntExtra("jmid", 0) );
        mValues.put("userId", User.getUserId());//社区医生id;
        mValues.put("mark", 1);
        //随访id
        int id = getIntent().getIntExtra("id", 0);
        if (id !=0){
            mValues.put("id", id);
            mValues.put("sfjlId", id);
        }
        getParents();
    }

    private void getParents(){
        Observable.create(new ObservableOnSubscribe<ParentsBean>() {
            @Override
            public void subscribe(ObservableEmitter<ParentsBean> emitter) throws Exception {
                Map<Object, Object> values = new HashMap<>();
                values.put("grjbxxId",getIntent().getIntExtra("jmid", 0));
                values.put("mark", 1);
                values.put("token", User.getToken());
                JSONObject jsonObject = new JSONObject(values);
                MyLogger.i(jsonObject.toString());
                String json = OkgoNetwork.post(Constant.baseurl+"online/xse/checkFM",jsonObject.toString());
                MyLogger.i(json);
                Gson gson = new Gson();
                emitter.onNext(gson.fromJson(json, ParentsBean.class));
            }
        }).compose(RxUtils.io_main()).subscribe(new ObserverOnNext<ParentsBean>() {
            @Override
            public void onNext(ParentsBean parentsBean) {
                if (parentsBean.getData()!= null){
                    mParentsBean = parentsBean;
                    View[] views = ((ET12ArchivesExtendableListAdapter) expandableListView.getExpandableListAdapter()).getConvertViews();
                    View view = views[0];
                    if (mParentsBean !=null && mParentsBean.getData() !=null){
                        mValues.put("jbxxXseId", mParentsBean.getData().getId());
                        ((EditText) view.findViewById(R.id.twelveChilds_fatherName)).setText(mParentsBean.getData().getFxm());
                        ((EditText) view.findViewById(R.id.twelveChilds_motherName)).setText(mParentsBean.getData().getMxm());
                        ((EditText) view.findViewById(R.id.twelveChilds_fatherJob)).setText(mParentsBean.getData().getFzy());
                        ((EditText) view.findViewById(R.id.twelveChilds_motherJob)).setText(mParentsBean.getData().getMzy());
                        ((EditText) view.findViewById(R.id.twelveChilds_fatherTel)).setText(mParentsBean.getData().getFdh() );
                        ((EditText) view.findViewById(R.id.twelveChilds_motherTel)).setText(mParentsBean.getData().getMdh());
                        ((TextView) view.findViewById(R.id.twelveChilds_fatherBirth)).setText(mParentsBean.getData().getFcsrq());
                        ((TextView) view.findViewById(R.id.twelveChilds_motherBirth)).setText(mParentsBean.getData().getMcsrq());
                    }
                }

            }
        });

    }



    public void showLoading(){
        mLoadingView = new LoadingViewDialog();
        mLoadingView.show(getSupportFragmentManager(),"" );
    }
    public void dismissLoading(){
        if (mLoadingView != null){
            mLoadingView.dismiss();
        }

    }

}